package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.pojo.Brand;
import com.leyou.pojo.Category;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService{

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 根据查询条件分页查询品牌信息
     * @Author Allen-fanxin
     * @Date 2020/9/23 12:21
     * @params [key, page, rows, sortBy, desc]
     * @Since version-1.0
     */
    public PageResult<Brand> queryBrandsByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {

        //初始化example对象
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();

        //根据name模糊查询，或根据首字母查询
        if (StringUtils.isNotBlank(key)){
            criteria.andLike("name","%"+key+"%").orEqualTo("letter",key);
        }

        PageHelper.startPage(page,rows);//添加分页条件

        //添加排序条件
        if (StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+" "+(desc?"desc":"asc"));
        }

        List<Brand> brands = this.brandMapper.selectByExample(example);

        //包装成pageInfo
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        //包装成分页结果集返回
        return new PageResult<Brand>(pageInfo.getTotal(),pageInfo.getList());

    }


    /**
     * 新增商品分类和品牌中间表数据
     * @Author Allen-fanxin
     * @Date 2020/9/24 10:57
     * @params [brand, cids]
     * @Since version-1.0
     */

    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        //新增品牌
        this.brandMapper.insertSelective(brand);
        //新增中间表
        cids.forEach(cid->{
            this.brandMapper.insertCategoryAndBrand(cid,brand.getId());
        });

    }

    public List<Category> queryCategoryByBid(Long bid) {
        return this.brandMapper.queryCategoryByBid(bid);
    }
    public List<Brand> queryBrandsByCid(Long cid) {

        return this.brandMapper.selectBrandsByCid(cid);
    }

    /**
     * 修改品牌信息
     * @Author Allen-fanxin
     * @Date 2020/9/25 10:29
     * @params [brand]
     * @Since version-1.0
     */
    public int updateBrand(Brand brand) {
        return this.brandMapper.updateByPrimaryKeySelective(brand);
    }

    /**
     * 根据id删除品牌信息
     * @Author Allen-fanxin
     * @Date 2020/9/25 12:17
     * @params [brand]
     * @Since version-1.0
     */
    public int deleteBrand(Long id) {
        this.brandMapper.deleteByPrimaryKey(id);
        return this.brandMapper.deleteCategoryAndBrand(id);
    }
}
